package org.breezeiot.protodecode.utils;

import com.alibaba.fastjson.JSON;
import org.breezeiot.protodecode.protocol.ProtocolWaterUtil;
import org.breezeiot.protodecode.dataobject.DataWaterExtend;
import org.breezeiot.protodecode.vo.xtkj.MeterDataVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class ProtocolXinTianUtil {
    private static Logger logger = LoggerFactory.getLogger(ProtocolXinTianUtil.class);

    public static MeterDataVO parseData(byte[] buf, int index) {
        MeterDataVO vo = new MeterDataVO();
        String commAddr = String.format("%02X%02X%02X%02X%02X%02X", buf[index + 5], buf[index + 4], buf[index + 3],
                buf[index + 2], buf[index + 1], buf[index]);
        vo.setCommAddr(commAddr);
        index += 6;
        vo.setItem((short) buf[index]);
        index++;
        String bcd = ProtocolUtils.getStringByBCD(buf, index, 4);
        index += 4;
        if (bcd.indexOf("EE") >= 0) {
            logger.info("cumulant:{} ignore... ", bcd);
            return vo;
        }
        bcd = ProtocolUtils.reverse(bcd, bcd.length());
        vo.setCumulant(ProtocolUtils.valueToDecimal(Long.parseLong(bcd), 2));
        byte[] status = new byte[2];
        System.arraycopy(buf, index, status, 0, 2);
        vo.setStatus(String.format("%02X %02X", status[0], status[1]));
        index += 6;
        short valveStatus = ProtocolWaterUtil.getStatus(status[0]);
        short valveFault = valveStatus > 1 ? (short) 1 : (short) 0;
        vo.setValveStatus(valveStatus);

        int value = (buf[index] & 0xff) + 200;
        vo.setVoltage((float) value / 100);
        index++;

        index += 6;
        Date dataTime = null;
        bcd = ProtocolUtils.getStringByBCD(buf, index, 5);
        if (bcd.indexOf("EE") < 0) {
            bcd = ProtocolUtils.reverse(bcd, bcd.length());
            dataTime = DateUtil.StrToDate(bcd, "yyMMddHHmm");
        }
        short batteryStatus = 0;
        if (!"FF".equalsIgnoreCase(String.format("%02X", status[0]))) {
            if ((status[0] & 0x04) != 0x00) {//电池电压欠压
                batteryStatus = 1;
            }
        }
        vo.setBatteryStatus(batteryStatus);
        logger.debug("meter data:{}", JSON.toJSONString(vo));
        if (dataTime == null) {
            logger.info("read time's format illegal.");
            return vo;
        }
        vo.setReadTime(dataTime);
        return vo;
    }

    private static DataWaterExtend buildWaterExtend(Integer pointId, Date dataTime, MeterDataVO data) {
        DataWaterExtend waterExtend = new DataWaterExtend();
        waterExtend.setPointId(pointId);
        waterExtend.setDataTime(dataTime);
        waterExtend.setVoltage(data.getVoltage());
        waterExtend.setMessage(JSON.toJSONString(data));
        return waterExtend;
    }
}
